import useSWR from 'swr';
import { getDictApi } from '@/api/system';
import { DictKey } from './dictKey';
import { useMemo } from 'react';
import { useAuthStore } from '@/store/useAuthStore';

export type DictItem = {
	label: string;
	value: string;
	remark: string;
};

export const useDict = (dictType: DictKey) => {
	const [data] = useDictLoading(dictType);
	return data;
};

export const useDictLoading = (dictType: DictKey) => {
	const token = useAuthStore(s => s.token);
	const { data, isLoading } = useSWR(
		token ? [`/system/dict/data/type/${dictType}`, token] : null,
		getDictApi
	);

	const dictArr = useMemo(() => {
		return [
			data?.map(item => ({
				label: item.dictLabel,
				value: item.dictValue,
				remark: item.remark
			})),
			isLoading
		] as const;
	}, [data, isLoading]);
	return dictArr;
};

